package com.atguigu.gmall.realtime.app.dws;

import com.atguigu.gmall.realtime.app.BaseSQLApp;
import com.atguigu.gmall.realtime.common.Constant;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/4/24 9:10
 */
public class ProvinceStatsApp extends BaseSQLApp {
    public static void main(String[] args) {
        new ProvinceStatsApp().init("ProvinceStatsApp", 4003, 1, "ProvinceStatsApp");
    }
    
    @Override
    public void handle(StreamTableEnvironment tEnv) {
        // 1. 从dwm_order_wide消费数据:通过ddel建立动态表与这个topic进行关联
        /*
        sql中的方法调用在as前还是在as后?
            在ddl中定义字段的时候, 是在as后
            
            在sqlQuery中在as 前(值是计算得到, 算完起个别名)
         */
        tEnv.executeSql("create table ow(" +
                            "   province_id bigint," +
                            "   province_name string, " +
                            "   province_area_code string, " +
                            "   province_iso_code string, " +
                            "   province_3166_2_code string, " +
                            "   split_total_amount decimal(20,2), " +
                            "   order_id bigint, " +
                            "   create_time string, " +
                            "   et as to_timestamp(create_time), " +
                            "   watermark for et as et - interval '3' second" +  // string -> timestamp(3)
                            ")with(" +
                            "  'connector' = 'kafka', " +
                            "  'properties.bootstrap.servers' = '" + Constant.KAFKA_BROKERS + "', " +
                            "  'properties.group.id' = 'ProvinceStatsApp', " +
                            "  'topic' = '"+ Constant.TOPIC_DWM_ORDER_WIDE +"', " +
                            "  'scan.startup.mode' = 'earliest-offset', " +
                            "  'format' = 'json'" +
                            ")");
       
        // 2. 开窗聚合
        tEnv.sqlQuery("select " +
                          " province_id, province_name, province_area_code, province_iso_code, province_3166_2_code," +
                          " tumble_start(et, interval '5' second) stt, " +
                          " tumble_end(et, interval '5' second) edt, " +
                          " sum(split_total_amount) total_amount, " +
                          " count(distinct(order_id)) ct " +
                          " from ow " +
                          " group by province_id, province_name, province_area_code, province_iso_code, province_3166_2_code, " +
                          " tumble(et, interval '5' second)")
            .execute()
            .print();
        
    }
}
